import axios from "axios";
import util from "./util";

const baseURL = "https://api.mch.weixin.qq.com";

const api = axios.create({
  baseURL,
});

export class WxpayV2Fix {
  constructor(options) {
    if (!options.appid || !options.mch_id || !options.keyV2) {
      throw new Error("invalid wxpay params");
    }
    this.options = options;
  }
  get apiKey() {
    return this.options.keyV2;
  }
  async post(path, body, config) {
    body.nonce_str = util.genNonceStr();
    body.appid = this.options.appid;
    body.mch_id = this.options.mch_id;
    body.sub_mch_id = body.sub_mch_id || this.options.sub_mch_id;
    if (!body.sub_mch_id) {
      throw new Error("缺少参数：子商户号");
    }
    body.sign = util.sign(body, this.apiKey);
    const res = await api.post(path, util.buildXML(body), config);
    return util.parseXML(res.data);
  }

  async profitsharingaddreceiver(body) {
    body.receiver = JSON.stringify(body.receiver);
    return this.post("/pay/profitsharingaddreceiver", body);
  }

  profitsharing(body) {
    body.receivers = JSON.stringify(body.receivers);
    return this.post("/secapi/pay/profitsharing", body);
  }
}
